/*
 * atmega16_ir_decode.c
 *
 * Created: 2011.12.14 14:23:44
 *  Author: Administrator
 */ 

#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>

void USART_txd(unsigned char data)
{
	while ( !( UCSRA & (1<<UDRE)) );
	UDR = data;
}

void USART_init()
{
	UBRRL=51;//51 for 8mhz, 109 for 16.9334
	UCSRB=(1<<RXCIE) | (1<<RXEN) | (1<<TXEN);
	UCSRC=(1<<URSEL) | (1<<UCSZ1) | (1<<UCSZ0);
	
	USART_txd('\n');
	
	USART_txd(0xaa);
	USART_txd(0x55);
	USART_txd(0x55);
	USART_txd(0xaa);
}
//unsigned char irdata[4]={0};
//unsigned char c=0,_c=0;
//#define IR (PIND&0b00000100)
//ISR(INT0_vect)
//{
	//USART_txd(0xff);
	//
		//irdata[0]=irdata[1]=irdata[2]=irdata[3]=0;
		//_delay_ms(8);
		//while(!IR);
		//if(IR)
		//{//test(0x11);
			//_delay_ms(4);
			//while(IR);
			////_delay_us(500);
			//if(!IR)
			//{//test(0x22);
				//c=0;
				//while(c++<4)
				//{
					//_c=0;
					//while(_c++<8)
					//{
						////_delay_us(100);
						//while(!IR);
						//if(IR)
						//{//test(0x33);
							//_delay_us(850);
							//irdata[c]>>=1;
							//if(IR)
							//{//test(0x01);
								//irdata[c]|=0x80;
							//}
							//else
							//{//test(0);
							//}
						//
						//}
						////test(0x33);
					//}
				//}
			//
			//}
		//
		//}
		//
	//USART_txd(irdata[0]);
	//USART_txd(irdata[1]);
	//USART_txd(irdata[2]);
	//USART_txd(irdata[3]);
//}

unsigned short time,last_time,t;

ISR(TIMER1_CAPT_vect)
{
	time=ICR1;
	if ((TCCR1B>>6)&1==0)
	{
		TCCR1B|=0b01000000;
	}
	else
	{
		TCCR1B&=~0b01000000;
	}	
	TIFR|=0b00100000;
	if (last_time>time)
	{
		t=0xffff-last_time+time+1;
	}	
	else
	{
		t=time-last_time;		
	}
	last_time=time;
	USART_txd(t>>8);
	USART_txd(t);
	
	//for (t=0;t<14;t++)
	//{
		//USART_txd(0);
	//}
}

int main(void)
{
	TIMSK=0X20;
	TCCR1B=2;
	
	//GICR |= (1 << INT0);
	sei();
	
	USART_init();
	
    while(1);
}